package com.Algorithm.binarySearchNoRecursion;

/**
 * 二分查找非递归实现
 *
 * @author MaoLin Wang
 * @date 2019/11/1419:15
 */
public class BinarySearchNoRecur {
    public static void main(String[] args) {
        int[] arr={1,3,8,10,11,67,100};
        int index=binarySearch(arr,1);
        System.out.println(index);
    }

    /**
     * 非递归实现
     *
     * @param arr
     * @param target
     * @return 返回待查询的下标 -1表示未找到
     */
    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid] == target){
                return mid;
            }else if (arr[mid]>target){
                //向左查询
                right=mid-1;
            }else{
                left=mid+1;
            }
        }
        return -1;
    }
}
